#!/usr/bin/env python
##@brief main file of this project.
#make plugin manager, dbconnector to use and parsing

from time import sleep
from os import path, chdir

from dbconnect import MainDBConnector
from pluginmanager import PluginManager
import twitterconnect as twtc
import re

##main function.
if __name__ == "__main__":
	# change current directory to file exists
	chdir(path.dirname(path.realpath(__file__)))

	dbc = MainDBConnector('twitter.db')
	plm = PluginManager('plugins')

	plm.load_plugin('echo')
	plm.load_plugin('randomanswer')

	consumer_key, consumer_secret = dbc.getConsumer()
	access_token, access_secret = dbc.getAccessTokens()[0]
	
	api = twtc.Api(consumer_key, consumer_secret)
	user = api.userLogin(access_token, access_secret)

	try:
		while True:
			mts = user.getMentions()
			for mt in mts:
				mt_text = re.sub(u"@[^ ]+ ", "", mt.text)
				print mt_text
				reply_string = plm.getReply(username=mt.user.screen_name, text=mt_text)
				print reply_string
				user.replyTo(mt.id, reply_string)
				user.setLastMention(mt.id)
			sleep(5)
	except KeyboardInterrupt:
		pass

	plm.unloadAll()
	dbc.close()
